/**
 * Wihidum - Efficient Broker Hierarchy for Publish Subscribe Middleware
 *
 * License      :   Apache License 2.0
 * Home Page    :   http://code.google.com/p/wihidum/
 * Mailing List :   wihidum@googlegroups.com
 */

package lk.mrt.cse.wihidum.storage;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import java.util.ArrayList;
import java.util.List;

public class BrokerDAO implements BrokerManager {

    Session session = null;
    private static final Logger logger = Logger.getLogger(BrokerDAO.class);

    public BrokerDAO() {
        this.session = DataBaseManager.getSessionFactory().getCurrentSession();
    }

    public boolean saveBroker(Broker broker) {
        try {
            Transaction tx = session.beginTransaction();
            session.save(broker);
            tx.commit();
            logger.info("Broker saved successfully");
            return true;
        }
        catch (HibernateException ex) {
            logger.error("Error in saving broker", ex);
            return false;
        }
    }

    public boolean deleteBroker(Broker broker) {
        try {
            Transaction tx = session.beginTransaction();
            Criteria criteria = session.createCriteria(Broker.class)
                    .add(Restrictions.eq("id", broker.getId()));
            ArrayList<Broker> searchedList = (ArrayList<Broker>) criteria.list();
            Broker b = searchedList.get(0);
            session.delete(b);
            tx.commit();
            logger.info("Broker deleted successfully");
            return true;

        }
        catch (HibernateException ex) {
            ex.printStackTrace();
            return false;
        }
    }

    public List<Broker> getBrokers() {
        try {
            session.beginTransaction();
            Criteria criteria = session.createCriteria(Broker.class);
            return (ArrayList<Broker>) criteria.list();
        }
        catch (HibernateException ex) {
            ex.printStackTrace();
            return new ArrayList<Broker>();
        }
    }
}
